﻿using System.IO;
using UnityEngine;
using System.Collections.Generic;
namespace GX
{
    public static class LangManager
    {
        public const string Default_Seperator = ":";

        static string _seperator = Default_Seperator;
        static readonly Dictionary<string, string> kvs = new Dictionary<string, string>();

        static public void Initialize(string path)
        {
            if (string.IsNullOrEmpty(path))
                return;
            var ta = Resources.Load<TextAsset>(path);
            if (null == ta)
                return;
            Parse(ta.text);
        }
        static public void Parse(string text)
        {
            int numSeperator = seperator.Length;
            string line;
            int index;
            string key, value;
            var sr = new StringReader(text);
            while (sr.Peek() != -1)
            {
                if (!string.IsNullOrEmpty(line = sr.ReadLine()))
                {
                    index = line.IndexOf(seperator);
                    if (index != -1)
                    {
                        key = line.Substring(0, index);
                        value = line.Substring(index + numSeperator);
                        kvs[key] = value;
                        Debug.Log(string.Format("{0} -> {1}", key, value));
                    }
                }
            }
            sr.Close();
            sr.Dispose();
        }
        static public string seperator
        {
            get { return _seperator; }
            set
            {
                _seperator = string.IsNullOrEmpty(value) ? Default_Seperator : value;
            }
        }
        static public bool HasKey(string key)
        {
            return kvs.ContainsKey(key);
        }
        static public string GetString(string key)
        {
            string v;
            if (kvs.TryGetValue(key, out v))
                return v;
            return null;
        }
        static public int GetInt(string key)
        {
            string s = GetString(key);
            if (string.IsNullOrEmpty(s))
                return 0;
            int v;
            if (int.TryParse(s, out v))
                return v;
            return 0;
        }
        static public float GetFloat(string key)
        {
            string s = GetString(key);
            if (string.IsNullOrEmpty(s))
                return 0;
            float v;
            if (float.TryParse(s, out v))
                return v;
            return 0f;
        }
        static public bool GetBool(string key)
        {
            string s = GetString(key);
            if (string.IsNullOrEmpty(s))
                return false;
            bool v;
            if (bool.TryParse(s, out v))
                return v;
            return false;
        }
    }
}